<?php

class TwitterSearch
{
  protected $_query;
  
  public function __construct( $query )
  {
    $this->_query = $query;
  }
  
  public function _makeTwitterApiSearchRequest( $params = null )
  {
    $urlData = array(
      'host' => 'http://search.twitter.com',
      'target' => 'search.atom',
      'query_string' => '',
      );
    $params['q'] = $this->_query;
    foreach( $params as $param => $value ) {
      $q[] = $param.'='.urlencode($value);
    }
    $urlData['query_string'] = implode('&',$q);
    $request = new CustomHttpRequest($urlData);
    $content = $request->getContent();
    return $content;        
  }
  
  public function getTweets( $params = null )
  {
    $params = Collection::consolidate(array(
      'tweets' => 15,
      'page' => 1,
      ),$params);
    
    $params['rpp'] = $params['tweets'] < 100 ? $params['tweets'] : 100;
    $pages = ceil($params['tweets']/$params['rpp']);
    $tweets = $params['tweets'];
    unset($params['tweets']);

    $entries = array();
    $params['since_id'] = isset($params['since_id']) ? $params['since_id'] : null;
    for( $i = 1; $i <= $pages; $i++ ) {
      $p = $params;
      $p['page'] = $i;
      $new = $this->_getEntries($p);
      $entries = array_merge($entries,$new);
      end($entries);
      $entry = current($entries);
      if( $entry ) {
        $params['since_id'] = $entry['id'];
      }
    }
    $entries = array_splice($entries,0,$tweets);
    return $entries;
  }
  
  protected function _getEntries( $params = null )
  {
    $result = array();
    $content = $this->_makeTwitterApiSearchRequest($params);
    $xml = new SimpleXMLElement($content);
    foreach( $xml->entry as $entry ) {
      preg_match('/:([0-9]+)$/',(string)$entry->id,$match);
      $id = $match[1];
      $n = (string)$entry->author->name;
      preg_match('/^(.*?)\((.*?)\)$/',$n,$match);
      if( isset($match[1]) && isset($match[2]) ) {
        $login = trim($match[1]);
        $name = trim($match[2]);
      } else {
        $login = '';
        $name = $n;
      }
      $result[] = array(
        'id' => $id,
        'href' => (string)($entry->link->attributes()->href),
        'title' => (string)$entry->title,
        'author_name' => $name,
        'author_login' => $login,
        'author_uri'  => (string)$entry->author->uri
        );
    }
    unset($xml);
    return $result;
  }
}